<?php

namespace app\controllers;

use Yii;
use yii\helpers\Url;
use app\Models\User;
use app\models\Weather;
use yii\web\Response;
use yii\filters\VerbFilter;

class WeatherController extends \yii\web\Controller
{

   /**
     * @inheritDoc
     */
    public function behaviors()
    {
        return array_merge(
            parent::behaviors(),
            [
                'verbs' => [
                    'class' => VerbFilter::className(),
                    'actions' => [
                        'delete' => ['POST'],
                    ],
                ],
            ]
        );
    }

  public function actionView($regionId) {
    $response = Yii::$app->response;
    if (Yii::$app->user->isGuest) {
      $response->format = \yii\web\Response::FORMAT_JSON;
      $response->statusCode = 401;
      return ['message' => 'Неверные авторизационные данные'];
    } 

    // Проверяем корректность accountId
    if ($regionId === null || !ctype_digit($regionId) || $regionId <= 0) {
        $response->format = \yii\web\Response::FORMAT_JSON;
        $response->statusCode = 400;
        return ['message' => 'regionId должен быть целым положительным числом'];
    }

    $model =  Weather::findOne(['id' => $regionId]);     

    if ($model === null) {
        $response->format = \yii\web\Response::FORMAT_JSON;
        $response->statusCode = 404;
        return ['message' => 'Регион с regionld не найден'];
    }
  
    return $this->render('view', [
      'model' => $model,
    ]);
  }

  public function actionCreate() {
    $response = Yii::$app->response;
    if (Yii::$app->user->isGuest) {
      $response->format = \yii\web\Response::FORMAT_JSON;
      $response->statusCode = 401;
      return ['message' => 'Неверные авторизационные данные'];
    }

    $model = new Weather();

    if ($this->request->isPost) {
        if ($model->load($this->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }
    } else {
        $model->loadDefaultValues();
    }

    return $this->render('create', [
        'model' => $model,
    ]);
  }

  public function actionUpdate($regionId) {
    $response = Yii::$app->response;
    if (Yii::$app->user->isGuest) {
      $response->format = \yii\web\Response::FORMAT_JSON;
      $response->statusCode = 401;
      return ['message' => 'Неверные авторизационные данные'];
    } 

    // Проверяем корректность accountId
    if ($regionId === null || !ctype_digit($regionId) || $regionId <= 0) {
        $response->format = \yii\web\Response::FORMAT_JSON;
        $response->statusCode = 400;
        return ['message' => 'regionId должен быть целым положительным числом'];
    }


    $model =  Weather::findOne(['id' => $regionId]);  

    if ($model === null) {
      $response->format = \yii\web\Response::FORMAT_JSON;
      $response->statusCode = 404;
      return ['message' => 'Регион с regionld не найден'];
    }

    if ($this->request->isPost && $model->load($this->request->post()) && $model->save()) {
        return $this->redirect(['view', 'id' => $model->id]);
    }

    return $this->render('update', [
        'model' => $model,
    ]);
  }

  public function actionDelete($regionId) {
    $response = Yii::$app->response;
    if (Yii::$app->user->isGuest) {
      $response->format = \yii\web\Response::FORMAT_JSON;
      $response->statusCode = 401;
      return ['message' => 'Неверные авторизационные данные'];
    } 

    // Проверяем корректность accountId
    if ($regionId === null || !ctype_digit($regionId) || $regionId <= 0) {
        $response->format = \yii\web\Response::FORMAT_JSON;
        $response->statusCode = 400;
        return ['message' => 'regionId должен быть целым положительным числом'];
    }
    
    $model =  Weather::findOne(['id' => $regionId]);  

    if ($model === null) {
      $response->format = \yii\web\Response::FORMAT_JSON;
      $response->statusCode = 404;
      return ['message' => 'Регион с regionld не найден'];
    }


    $model->delete();

    return $this->redirect(['/']);
  }

  public function actionSearch($startDateTime = null, $endDateTime = null, $regionId = null, $weatherCondition = null, $form = 0, $size = 10) {

    $response = Yii::$app->response;
    if (Yii::$app->user->isGuest) {
      $response->format = \yii\web\Response::FORMAT_JSON;
      $response->statusCode = 401;
      return ['message' => 'Неверные авторизационные данные'];
    }

    // Проверка формата даты
    if (($startDateTime && !\DateTime::createFromFormat(\DateTime::ISO8601, $startDateTime)) || 
        ($endDateTime && !\DateTime::createFromFormat(\DateTime::ISO8601, $endDateTime))) {
        $response->statusCode = 400;
        return ['error' => 'measurementDateTime is not in ISO-8601 format'];
    }

    // Проверка допустимых значений для weatherCondition
    $validConditions = ["CLEAR", "CLOUDY", "RAIN", "SNOW", "FOG", "STORM"];
    if ($weatherCondition && !in_array($weatherCondition, $validConditions)) {
        $response->statusCode = 400;
        return ['error' => 'Invalid weatherCondition value'];
    }

    if ($form < 0 || $size <= 0) {
        $response->statusCode = 400;
        return ['error' => 'Invalid form or size parameter'];
    }

    $query = (new \yii\db\Query())
        ->select(['*'])
        ->from('weather');
        

      if (!is_null($startDateTime) && !is_null($endDateTime)) {
        $query->andWhere(['between', 'measurementDateTime', $startDateTime, $endDateTime]);
      }
  
      if (!is_null($regionId)) {
        $query->andWhere(['regionId' => $regionId]);
      }
  
      if (!is_null($weatherCondition)) {
        $query->andWhere(['weatherCondition' => $weatherCondition]);
      }

    $query->offset($form)->limit($size);

    $query->orderBy(['id' => SORT_ASC]);

    $weathers = $query->all();

    return $weathers;
  }
}